<template>
	<view class="start-naintenance">
		<navBar :title="!showButton ? '病害维修' : '新增维修'"></navBar>
		<view class="content-colot"></view>
		<u-tabs :list="list" :scrollable='false' lineWidth='200' :activeStyle="{color:'#2F80ED'}" lineHeight='1'
			@change='change'></u-tabs>
		<serviceInformation  v-show="show" ref="serviceIn" :dateList="dateList" :information="information" :recordInfo="recordInfo"></serviceInformation>
		<scroll-view v-show="!show" :scroll-y="true" :style="{height:`calc(100vh - 180rpx - 44px - 160rpx)`}">
			<materialInformation  ref="newReduceRef" :material="material"></materialInformation>
		</scroll-view>		
		<view class="footer-button">
			<view class="button-placeholder"></view>
			<view class="button-group">
				<button  @click="staAndsub(0)" :loading="loading" class="button-warn" v-if="!showButton">暂存</button>
				<button  @click="staAndsub(1)" :loading="loading" class="button-primary">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import serviceInformation from './serviceInformation.vue'
	import materialInformation from './materialInformation.vue'
	import { 	uploadFile } from '@/utils/request'
	import { commit, saveRepairOrder, repairDetail,  } from '@/api/engineeringMaintenance/maintenanceTask.js'
	import { getPicture, deleteImg, doc_deleteAttachs } from '@/api/doc.js'
	export default {
		name: 'startMaintenance',
		components: {
			serviceInformation,
			materialInformation
		},
		provide(){
			return {
				grandFatherObj:() => {
					return this.recordInfo
				}
			}
		},
		data() {
			return {
				list: [{
						name: '维修信息'
					},
					{
						name: '材料消耗'
					}
				],
				dateList: {},
				show: true,
				information: {},
				material: [],
				loading: false,
				recordInfo:{},
				showButton:'',
				diseaseOrderRequest:{},
				isRequest:false
			}
		},
		onLoad(options) {
			console.log(options.buttonType);
			if(options.lineSiteInfo) {
				this.showButton = options.buttonType
				this.recordInfo = JSON.parse(options.lineSiteInfo)
				this.recordInfo.btnType = this.showButton		
				console.log(this.recordInfo, '00')
			}
			
			const eventChannel = this.getOpenerEventChannel();
			// 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
			eventChannel.on('getLists', (data) => {
				this.dateList = data.data[data.e]
				console.log(this.dateList, '传递的数据');
				//图片
				if (this.dateList.docId) {
					this.getItemImage(this.dateList.docId).then(res => {
						this.$set(this.dateList, 'imgs', res)
					})
				}
				//视频
				if(this.dateList.videoDocId) {
					this.getVideoList(this.dateList.videoDocId).then(res => {
						this.$set(this.dateList, 'videoList', res)
					})
				}else {
					this.$set(this.dateList, 'videoList', [])
				}
				
				
				this.reDetails()
				// console.log(this.dateList, '传递的对象');

			})
			
			this.$eventBus.$off("sendGrandsonData").$on('sendGrandsonData', data => {
			  console.log(data, '孙子组件的信息');
			  this.diseaseOrderRequest = {...data}
			})
		},
		methods: {
			/**
			 * 获取到docId中的图片并且拼成网络路径格式
			 * @param {Number} docId
			 * @return {String} //拼好的网络路径格式
			 */
			async getItemImage(docId) {
				return await new Promise((resolve, reject) => {
					getPicture({
						docId
					}).then(res => {
						let imgResult = res.result.filter(item => item.contentType.substring(0, item
							.contentType.indexOf("/")) === 'image')
						resolve(imgResult.map(it => ({
							url: this.$config.IMG_FILE_URL + it.fileName,
							id: it.id
						})) || []);
					}).catch(err => reject(err))
				})
			},
			async getVideoList(docId) {
				return await new Promise((resolve, reject) => {
					getPicture({
						docId
					}).then(res => {
						let videoResult = res.result.filter(item => item.contentType.substring(0, item
							.contentType.indexOf("/")) === 'video')
						resolve(videoResult.map(it => ({
							url: this.$config.VIDEO_URL + it.fileName,
							id: it.id
						})) || []);
					}).catch(err => reject(err))
				})
			},
			change(e) {
				if (e.name === '维修信息') {
					this.show = true
				} else {
					this.show = false
				}
			},
			// 维修详情
			reDetails() {
				let params = {
					id: this.dateList.id
				}
				// console.log(this.$refs.serviceIn, '维修详情');
				repairDetail(params).then(res => {
					if (res.status === 1 && res.success) {
						// console.log(res.result, '维修详情');
						this.repId = res.result.id
						this.information = res.result
						this.$set(this.information, 'repairOrderStateName', this.dateList.repairOrderStateName)
						if (res.result.materialList && res.result.materialList.length > 0) {
							this.material = res.result.materialList || []
						}


					}
				})
			},
			getTempPath(url) {
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url,
						success: (res) => {
							console.error(res);
							resolve(res)
						},
						fail: (err) => {
							console.error(err, 'err');
						}
					})
				})
			}, 
			// 0暂存 1提交
			async staAndsub(type) {
				if (this.loading) return
				this.loading = true
				//判断是否还有视频正在上传中
				// let taskArr = this.$refs.serviceIn.videoFileList
				// taskArr = taskArr.filter(item => item.uploadStatus)
				// if(taskArr.length > 0){
				// 	uni.showToast({
				// 		title:'还有视频正在上传中,请稍后再试',
				// 		icon:'none',
				// 		mask:true
				// 	})
				// 	this.loading = false
				// 	return
				// }
				let repair = this.$refs.serviceIn.formData
				let fileList1 = this.$refs.serviceIn.fileListImg
				if (!repair.repairDate) {
					uni.showToast({
						title: `请填写必填数据`,
						icon: 'none'
					})
					this.loading = false
					return

				}

				let newList = this.$refs.newReduceRef.rowBox
				//防止两个规格型号都没有的情况
				for(let item of newList) {
					if(!item.special) {
						item.special = item.processName + '/' + item.subDeviceTypeId
					}
				}
				//通过数组对象中的count字段判断这个对象有没有值
				// console.log(newList, '材料原始数据');
				newList = newList.filter(it => it.count !== 0)
				// if (newList.length > 1) {
					for (let i = 0; i < newList.length; i++) {
						if (newList[i].model === '') {
							// this.isClick = false
							this.loading = false
							return uni.showToast({
								title: `请填写第${i + 1}项的材料型号数据`,
								icon: 'none'
							})
						}
						if(newList[i].shelfLife <= 0) {
							// this.isClick = false
							this.loading = false
							return uni.showToast({
								title: `第${i + 1}项的消耗量应大于0`,
								icon: 'none'
							})
						}
					}
				// }
				// 提交时判断数组中是否有重复的材料名称和材料型号(special值)
				const isRepeat = newList.some(r => newList.filter(r1 => r1.special === r.special).length > 1)
				// console.log(isRepeat, '是否重复');
				if (isRepeat) {
					// this.isClick = false
					 uni.showToast({
						title: '存在重复的材料名称+材料型号!',
						icon: 'none'
					})
					this.loading = false
					return
				}
				console.log(newList, '-------刘总要的数据');
				// return
				let newMap = newList.map(item => ({
					num: Number(item.shelfLife),
					unit: item.unit,
					deviceTypeId: item.subDeviceTypeId,
					deviceTypeAttributeId:item.materialId,
					subDeviceTypeName: item.processName.split("/")[0] || '',
					specificationModel: item.model,
					deviceTypeName:item.processName.split("/")[1] || '',
				})).filter(item => item.num !== 0)
				await this.$refs.serviceIn.deleteFiles()
				await this.$refs.serviceIn.uploadFileListAttach()
				let params = {
					id: this.repId,
					repairDate: repair.repairDate || '',
					voucherDocId: this.$refs.serviceIn.docId || '',
					materialList: newMap,
					remark:this.$refs.serviceIn.remark,
					measure:this.$refs.serviceIn.measure,
					repairMaterials: this.$refs.serviceIn.dataArr,
					preConstructionDocId: this.$refs.serviceIn.preConstructionDocId,
					afterConstructionDocId: this.$refs.serviceIn.afterConstructionDocId,
					middleConstructionDocId:this.$refs.serviceIn.middleConstructionDocId, //维修中图片
					maintainConstructionDocId:this.$refs.serviceIn.maintainConstructionDocId, //维修视频
					diseaseOrderId: type === 0 ? undefined : this.information.diseaseOrderId,
					pmId:this.dateList.pmId,
					pmName:this.dateList.pmName
				}
				// console.error(this.$refs.serviceIn.removeFileSet,'kanknknk')
				// console.error(params, '入参----------329行')
				// return
				// 删除视频记录的视频id
				// let arr = [...this.$refs.serviceIn.removeFileSet] || []
				// if(arr.length) {
				// 	await doc_deleteAttachs(arr)
				// }
				if (type === 0) {
					
					let resultTemporary = await saveRepairOrder(params)
					if (resultTemporary.status === 1 && resultTemporary.success) {
						this.isRequest = true
						uni.showToast({
							title: resultTemporary.message,
							icon: 'none'
						})
						uni.navigateBack();
						this.$refs.serviceIn.fileListImg = []
					}
					
				} else {
					if(this.showButton) {
						console.log('新增维修');
						this.$set(this.diseaseOrderRequest, 'projectId', uni.getStorageSync('isOwner'))
						this.$set(this.diseaseOrderRequest, 'followup','新增')
						this.$set(this.diseaseOrderRequest, 'orderType','add')
						this.$set(this.diseaseOrderRequest, 'lineSiteSectionType',this.recordInfo.lineSiteSectionType)
						this.$set(this.diseaseOrderRequest,'createUserName', this.$store.getters.name)
						this.$set(this.diseaseOrderRequest, 'createDate',new Date().getTime())
						let arr = [
							!this.diseaseOrderRequest.startMileageFront,
							!this.diseaseOrderRequest.startMileageAfter,
							!this.diseaseOrderRequest.endMileageFront,
							!this.diseaseOrderRequest.endMileageAfter
						], isTrue = arr.every( it => !it), isNull = arr.every(it => it)
						if(!isTrue && !isNull){
							uni.showToast({
								title:'请检查数据格式',
								icon:'none'
							})
							this.loading = false
							return
						}
						
						let arr2 = [
							!this.diseaseOrderRequest.startNumber,
							!this.diseaseOrderRequest.endNumber,
						], isTrue2 = arr2.every( it => !it), isNull2 = arr2.every(it => it)
						if(!isTrue2 && !isNull2){
							uni.showToast({
								title:'请检查数据格式',
								icon:'none'
							})
							this.loading = false
							return
						}

						if (!this.validFormItem(this.diseaseOrderRequest)) return

						params.diseaseOrderRequest = this.diseaseOrderRequest
					}
					let resultCommit = await commit(params)
					if (resultCommit.status === 1 && resultCommit.success) {
						this.isRequest = true
						uni.showToast({
							title: '提交成功',
							icon: 'none'
						})
						uni.navigateBack();
						this.$refs.serviceIn.fileListImg = []
					}else {
						this.loading = false
					}					
				}
			},
			/**
			 * 校验表单必填
			 */
			validFormItem(obj) {
				// console.log(!obj.team,'验证');
				if (!obj.diseaseStatus) {
					uni.showToast({
						title: '请选择病害现状',
						icon: 'none'
					})
					this.loading = false
					return false
				}
			
				if (!obj.diseaseGrade) {
					uni.showToast({
						title: '请选择病害等级',
						icon: 'none'
					})
					this.loading = false
					return false
				}
				if (!obj.team) {
					uni.showToast({
						title: '请选择施工班组',
						icon: 'none'
					})
					this.loading = false
					return false
				}
				
				if (obj.lineSiteSectionType === 'qj') {
					let regRing = false
					let regMileage = false
					let regOther = false
					if (!obj.startNumber && !obj.endNumber) {
						regRing = true
					}
					if(!obj.startMileageFront && !obj.startMileageAfter && !obj.endMileageFront && !obj.endMileageAfter) {
						regMileage = true
					}
					if(!obj.others) {
						regOther = true
					}
					if(regRing && regMileage && regOther) {
						uni.showToast({
							title: '里程,环号和其他必填其一',
							icon: 'none'
						})
						this.loading = false
						return false
					}
					
					
				}
				
				
				
				if (obj.lineSiteSectionType === 'cz') {
					// debugger
					if (!obj.stationLocation && !obj.others) {
						uni.showToast({
							title: '位置选择和其他必填其一',
							icon: 'none'
						})
						this.loading = false
						return false
					}
					
				}
				if (obj.lineSiteSectionType !== 'qj' && obj.lineSiteSectionType !== 'cz') {
					if (!obj.others) {
						uni.showToast({
							title: '请填写位置',
							icon: 'none'
						})
						this.loading = false
						return false
					}
					
				}				
				this.loading = false
				return true
			},
			
		}

	}
</script>

<style lang="scss" scoped>
	.start-naintenance {
		/* #ifdef MP-WEIXIN */
			padding-top: 180rpx;
		/* #endif */
		.content-colot {
			height: 40rpx;
			background: #F5F7FA;
		}

		.btn_box {
			height: 100rpx;
			.btn_group {
				z-index: 10;
				display: flex;
				align-items: center;
				justify-content: space-between;
				// margin-top: 100rpx;
				position: fixed;
				bottom: 0;
				width: 100%;
				// margin-left: 40rpx;

			}
		}
	}
</style>
